<template>
  <div class="common-container">
    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增数据集
        </el-button>
        <el-input
          v-model="queryParams.search"
          placeholder="输入关键字搜索"
          style="width: 250px; margin-left: 15px"
          clearable
          @keyup.enter="fetchDatasetList"
          @clear="fetchDatasetList"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="fetchDatasetList">
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-select
          v-model="queryParams.data_source_id"
          placeholder="选择数据源"
          clearable
          style="width: 180px; margin-left: 10px"
          @change="fetchDatasetList"
        >
          <el-option
            v-for="item in dataSourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="queryParams.category"
          placeholder="选择分类"
          clearable
          style="width: 150px; margin-left: 10px"
          @change="fetchDatasetList"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table :data="datasetList" style="width: 100%" border stripe v-loading="loading">
        <el-table-column prop="id" type="index" width="80" />
        <el-table-column prop="name" label="数据集名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="150" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.category">{{ scope.row.category }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="sync_enabled" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.sync_enabled)">
              {{ getStatusLabel(scope.row.sync_enabled) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="original_name" label="表名" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="330" fixed="right">
          <template #default="scope">
            <div class="action-container">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  class="action-button"
                  type="primary"
                  circle
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="管理字段" placement="top">
                <el-button
                  class="action-button"
                  type="success"
                  circle
                  size="small"
                  @click="handleViewFields(scope.row)"
                >
                  <el-icon><Grid /></el-icon>
                </el-button>
              </el-tooltip>

              <!-- <el-tooltip content="结构变更" placement="top">
                <el-button
                  class="action-button"
                  type="info"
                  circle
                  size="small"
                  @click="handleViewChanges(scope.row)"
                >
                  <el-icon><TakeawayBox /></el-icon>
                </el-button>
              </el-tooltip> -->
              <el-tooltip content="角色授权" placement="top">
                <el-button
                  class="action-button"
                  type="warning"
                  circle
                  size="small"
                  @click="handleRoleAccess(scope.row)"
                >
                  <el-icon><User /></el-icon>
                </el-button>
              </el-tooltip>
              <!-- <el-tooltip content="同步数据" placement="top">
                <el-button
                  class="action-button"
                  type="success"
                  circle
                  size="small"
                  @click="handleSync(scope.row)"
                >
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </el-tooltip> -->
              <el-tooltip content="删除" placement="top">
                <el-button
                  class="action-button"
                  type="danger"
                  circle
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 数据集表单对话框 -->
    <dataset-form
      v-if="formDialogVisible"
      v-model="formDialogVisible"
      :dataset-id="selectedDatasetId"
      :is-add="isAdd"
      @success="fetchDatasetList"
    />

    <!-- 字段管理抽屉 -->
    <field-management v-model="fieldDialogVisible" :dataset-id="selectedDatasetId" />

    <!-- 结构变更管理对话框 -->
    <change-management
      v-if="changeDialogVisible"
      v-model="changeDialogVisible"
      :dataset-id="selectedDatasetId"
    />

    <!-- 角色授权管理对话框 -->
    <role-dataset-access
      v-if="roleAccessDialogVisible"
      v-model="roleAccessDialogVisible"
      :dataset-id="selectedDatasetId"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Search,
  Grid,
  TakeawayBox,
  RefreshRight,
  User,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDatasetList, deleteDataset, syncDataset, checkDatasetStructure } from '@/api/dataset'
import { getDataSourceList } from '@/api/datasource'
import DatasetForm from './components/DatasetForm.vue'
import FieldManagement from './components/FieldManagement.vue'
import ChangeManagement from './components/ChangeManagement.vue'
import RoleDatasetAccess from './components/RoleDatasetAccess.vue'

// 定义组件名
defineOptions({
  name: 'DatasetPage',
})

// 状态
const datasetList = ref([])
const loading = ref(false)
const formDialogVisible = ref(false)
const fieldDialogVisible = ref(false)
const changeDialogVisible = ref(false)
const roleAccessDialogVisible = ref(false)
const selectedDatasetId = ref(null)
const isAdd = ref(true)
const dataSourceOptions = ref([])

// 查询参数
const queryParams = reactive({
  search: '',
  data_source_id: '',
  category: '',
  skip: 0,
  limit: 10,
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 分类选项
const categoryOptions = [
  { label: '业务数据', value: '业务数据' },
  { label: '系统数据', value: '系统数据' },
  { label: '其他', value: '其他' },
]

// 获取数据集状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    active: '活跃',
    inactive: '未激活',
    syncing: '同步中',
    error: '错误',
  }
  return statusMap[status] || status
}

// 获取数据集状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    active: 'success',
    inactive: 'info',
    syncing: 'warning',
    error: 'danger',
  }
  return typeMap[status] || 'info'
}

// 加载数据源列表
const loadDataSources = async () => {
  try {
    const res = await getDataSourceList()
    if (res && res.items) {
      dataSourceOptions.value = res.items.map((item) => ({
        label: item.name,
        value: item.id,
      }))
    }
  } catch (error) {
    console.error('获取数据源列表失败:', error)
  }
}

// 获取数据集列表
const fetchDatasetList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      skip: (pagination.currentPage - 1) * pagination.pageSize,
      limit: pagination.pageSize,
      search: queryParams.search,
      data_source_id: queryParams.data_source_id,
      category: queryParams.category,
    }

    const res = await getDatasetList(params)

    if (res && res.data) {
      datasetList.value = res.data
      pagination.total = res.total || res.data.length
    } else {
      datasetList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取数据集列表失败:', error)
    ElMessage.error('获取数据集列表失败: ' + (error.message || '未知错误'))
    datasetList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 新增数据集
const handleAdd = () => {
  selectedDatasetId.value = null
  isAdd.value = true
  formDialogVisible.value = true
}

// 编辑数据集
const handleEdit = (row) => {
  selectedDatasetId.value = row.id
  isAdd.value = false
  formDialogVisible.value = true
}

// 管理字段
const handleViewFields = (row) => {
  selectedDatasetId.value = row.id
  fieldDialogVisible.value = true
}

// 查看结构变更
const handleViewChanges = async (row) => {
  try {
    loading.value = true
    // 先检查一下是否有变更
    await checkDatasetStructure(row.id)
    selectedDatasetId.value = row.id
    changeDialogVisible.value = true
  } catch (error) {
    console.error('检查结构变更失败:', error)
    ElMessage.error('检查结构变更失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 管理角色授权
const handleRoleAccess = (row) => {
  selectedDatasetId.value = row.id
  roleAccessDialogVisible.value = true
}

// 同步数据
const handleSync = (row) => {
  ElMessageBox.confirm(
    `确定要同步数据集 "${row.name}" 的数据吗？同步过程可能需要一些时间。`,
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      loading.value = true
      try {
        await syncDataset(row.id)
        ElMessage.success('数据同步已启动，请稍后刷新页面查看同步状态')
        // 短暂延迟后刷新列表
        setTimeout(() => {
          fetchDatasetList()
        }, 2000)
      } catch (error) {
        console.error('同步数据失败:', error)
        ElMessage.error('同步数据失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      ElMessage.info('已取消同步')
    })
}

// 删除数据集
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除数据集 "${row.name}" 吗？此操作将无法恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await deleteDataset(row.id)
        ElMessage.success('删除成功')
        fetchDatasetList()
      } catch (error) {
        console.error('删除数据集失败:', error)
        ElMessage.error('删除数据集失败: ' + (error.message || '未知错误'))
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchDatasetList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchDatasetList()
}

// 初始化
onMounted(() => {
  loadDataSources()
  fetchDatasetList()
})
</script>

<style scoped>
.common-container {
  padding: 20px;
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  align-items: center;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.action-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button {
  font-size: 12px;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>
